package com.easy.controller;

import com.easy.bean.User;
import com.easy.service.RegisterService;
import com.easy.util.EmailUtil;
import com.easy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("register")
public class RegisterController {

    @Autowired
    private RegisterService registerService;

    @Autowired
    private EmailUtil emailUtil;

    /**
     * 发送验证码（无论手机号是什么，都发到固定邮箱 1803237603@qq.com）
     */
    @PostMapping("/send-code")
    public Result sendCode(@RequestBody Map<String, String> body) {
        try {
            String phone = body.getOrDefault("phone", "");
            // 固定邮箱
            String email = "1803237603@qq.com";
            // 调用工具类生成并发送验证码
            String code = EmailUtil.generateAndSendCode(email);
            // 如果后续你要做校验，可以把 code 暂存到 Redis / Map
            System.out.println("手机号：" + phone + " 对应验证码：" + code);
            return Result.success("验证码已发送到邮箱");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("验证码发送失败");
        }
    }

    /**
     * 这是你原来的 register 方法（保持不变）
     */
    @PostMapping
    public Result register(@RequestBody User user) {
        try {
            User u = registerService.getByPhone(user.getPhone());
            if (u != null) {
                return Result.fail("用户已存在！");
            }
            if (!user.getPassword().equals(user.getReadpassword())) {
                return Result.fail("两次输入的密码不一致！");
            }
            registerService.register(user);
            return Result.success("注册成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("注册失败！");
        }
    }
}
